package com.douguo.recipe;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.douguo.recipe.network.Constant;
import com.douguo.recipe.network.GetEkArticleList;
import com.douguo.recipe.network.GetPhoto;
import com.douguo.recipe.network.Util;
import com.douguo.recipe.object.EkArticle;
import com.douguo.recipe.view.NavigationView;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.TextView;
import android.widget.Toast;

public class EKArticleListActivity extends EKActivity {
	
	private static final String TAG = "EKArticleListActivity";
	
	private ListView mListview;
//	private ProgressBar mProgressBar;
	private NavigationView mNavigationView;
	private View mFooter;
	
	
	private List<Map<String,Object>> mArticleList;
	private List<EkArticle> mArticles; 
	
	private SimpleAdapter mAdapter;
	
	
	
	private int mCurrentPos = 0;
	private String mSortId;
	private String mSortTitle;
	private boolean isAutoDownloadThumb;

	private static final int PAGESIZE = 10;
	private static final int MAX_RETRY_TIMES = 1;
	
	private static final int ARTICLE_NUMBER = 10;
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Constant.GET_EK_ARTICLES:
				List<EkArticle> articles = (List<EkArticle>) msg.obj;
//				mProgressBar.setVisibility(View.GONE);
				if(articles != null) {
					
					if(articles.size() < PAGESIZE || articles.size() == 0) {
						isToLoad = false;
						enableFooter(false,false,false);
						Util.showLongToast(getApplicationContext(), R.string.noMoreArticle);
						return;
					}
					enableFooter(false,false,true);
					int i = 0;
					for(EkArticle article:articles){
						Map<String, Object> hm = new HashMap<String, Object>();
						hm.put("articleTitle", article.title);
						hm.put("articleSummary", article.excerpt);
						hm.put("articleId", article.id);
						hm.put("retry", 0);
						hm.put("articleThumbPath", article.thumb);
						hm.put("thumbLoaded", Boolean.FALSE);
						if (isAutoDownloadThumb) {
							hm.put("articleThumb", BitmapFactory.decodeResource(
									getResources(),
									R.drawable.cookdefault80_downloading));
						} else {
							hm.put("articleThumb", BitmapFactory.decodeResource(
									getResources(), R.drawable.cookdefault80));
						}
						mArticleList.add(hm);
//						if (isAutoDownloadThumb) {
//							getPhoto(mCurrentPos + i);
//						}
						i++;
					}
					
					mAdapter.notifyDataSetChanged();
					mListview.setVisibility(View.VISIBLE);
					mCurrentPos += articles.size();
					isToLoad =true;
					mArticles.addAll(articles);
				}
				else {
					isToLoad = false;
					enableFooter(false,true,false);
					Toast.makeText(getApplicationContext(), R.string.getEKListError, Toast.LENGTH_SHORT).show();
				}
				break;
			case Constant.GET_PHOTO: {
				int pos = msg.arg1;
				SoftReference<Bitmap> refBitmap = (SoftReference<Bitmap>) msg.obj;
				Map<String, Object> hm = mArticleList.get(pos);
				int retryTimes = (Integer) hm.get("retry");
				String thunmbPath = (String) hm.get("thumnbPath");
				if (refBitmap != null) {
					Bitmap bitmap = refBitmap.get();
					if (bitmap != null) {
						hm.put("articleThumb", bitmap);
						hm.put("thumbLoaded", Boolean.TRUE);
						
						Log.d(TAG, "thumb:" + bitmap.getHeight());
						mAdapter.notifyDataSetChanged();
					}

				} else if (refBitmap == null && retryTimes < MAX_RETRY_TIMES) {
					hm.put("retry", ++retryTimes);
					GetPhoto.getPhoto(pos, thunmbPath, mHandler);
				} else {
					hm.put("articleThumb", BitmapFactory.decodeResource(getResources(), R.drawable.cookdefault80));
				}
				
				break;
			}
			}
			}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ek_articlelist);
		Bundle bundle = getIntent().getExtras();
		isScrolling = false;
		mSortId = bundle.getString("sortId");
		isAutoDownloadThumb = Util.isDownloadPhotoPreferences(this);
		initData();
		initBundle();
		initUI();
		GetEkArticleList.GetHotEkArticleList(mSortId, mCurrentPos, ARTICLE_NUMBER, mHandler);
	}
	
	private void initBundle() {
		Intent intent = getIntent();
		if(intent != null) {
			Bundle bundle = intent.getExtras();
			mSortTitle = bundle.getString("title");
		}
	}
	
	private void initData() {
		mArticleList = new LinkedList<Map<String,Object>>();
		mAdapter = new EKListAdapter(this, mArticleList, R.layout.ek_articlelist_item, new String[]{"articleTitle","articleSummary","articleThumb","articleId"}, 
					new int[]{R.id.articlelist_title,R.id.articlelist_content,R.id.articlelist_thumb});
		mAdapter.setViewBinder(new ViewBinder() {
			
			@Override
			public boolean setViewValue(View view, Object data,
					String textRepresentation) {
				if(data instanceof String) {
					TextView tv = (TextView)view;
					tv.setText((String)data);
//					return true;
				}
				else if(data instanceof Bitmap) {
					ImageView iv = (ImageView)view;
					iv.setImageBitmap((Bitmap)data);
//					iv.setImageResource(R.drawable.bar_top);
//					return true;
				}
				return true;
			}
		});
		mArticles = new LinkedList<EkArticle>();
	}
	
	private void enableFooter(boolean wait,boolean retry,boolean more) {
		if(mFooter != null){
			LinearLayout waitLayout = (LinearLayout) mFooter.findViewById(R.id.nextTenArticlesLoading);
			LinearLayout retryLayout = (LinearLayout) mFooter.findViewById(R.id.articleRetryView);
			LinearLayout moreLayout = (LinearLayout) mFooter.findViewById(R.id.nextTenArticlesClick);
			moreLayout.setVisibility(more?View.VISIBLE:View.GONE);
			waitLayout.setVisibility(wait?View.VISIBLE:View.GONE);
			retryLayout.setVisibility(retry?View.VISIBLE:View.GONE);
			Button button = (Button) retryLayout.findViewById(R.id.btnRetry);
			button.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
//					if(isToLoad && totalItemCount - firstVisibleItem == visibleItemCount) {
//						Log.d(TAG, "totalItemCount:"+totalItemCount+";firstVisibleItem:"+firstVisibleItem+";visibleItemCount:"+visibleItemCount);
						GetEkArticleList.GetHotEkArticleList(mSortId, mCurrentPos, ARTICLE_NUMBER, mHandler);
						isToLoad = false;
						enableFooter(true,false,false);
//					}
					
				}
			});
			moreLayout = (LinearLayout) moreLayout.findViewById(R.id.nextTenArticlesClick);
			moreLayout.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
//					if(isToLoad) {
//						Log.d(TAG, "totalItemCount:"+totalItemCount+";firstVisibleItem:"+firstVisibleItem+";visibleItemCount:"+visibleItemCount);
//						GetEkArticleList.GetHotEkArticleList(mSortId, mCurrentPos, ARTICLE_NUMBER, mHandler);
////						isToLoad = false;
//						enableFooter(true,false,false);
//					}
				}
			});
		}
		
	}
	
	private void getPhoto(int position) {
		Map map = (Map) mAdapter.getItem(position);

		if (((!map.containsKey("gettingImg") || map.get("gettingImg") == Boolean.FALSE)) 
				&& map.containsKey("thumbLoaded") &&   map.get("thumbLoaded") == Boolean.FALSE) {
			GetPhoto.getPhoto(position, (String) map.get("articleThumbPath"),
					mHandler);
			map.put("gettingImg", Boolean.TRUE);
		}
	}
	
	private void initUI() {

		mNavigationView = new NavigationView(this, NavigationView.STATE_MAGAZINE);
		mListview = (ListView) findViewById(R.id.ek_articlelist_listview);
		mFooter = LayoutInflater.from(this).inflate(R.layout.ek_articlelist_footer, null);
		mListview.addFooterView(mFooter);
		
		mListview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterview, View view, int position,
					long arg3) {
				Intent intent = new Intent(getApplicationContext(),EKArticleActivity.class);
				if(adapterview.getAdapter().getItemViewType(position) != AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER){
					intent.putExtra("article_url", Constant.URL_GET_EK_ARTICLE + mArticles.get(position).id);
					intent.putExtra("title", mSortTitle);
					intent.putExtra("pos", getCurrentTabPos());
					intent.putExtra("article_title", mArticles.get(position).title);
					startActivity(intent);
				}
				else {
					 View nextTenView = view.findViewById(R.id.nextTenArticlesClick);
					 if(nextTenView != null && nextTenView.getVisibility() == View.VISIBLE){//下十个文章按钮可见
						GetEkArticleList.GetHotEkArticleList(mSortId, mCurrentPos, ARTICLE_NUMBER, mHandler);
						enableFooter(true,false,false);
					 }
				}
				
			}
		});
//		mListview.setVisibility(View.GONE);
//		mProgressBar = (ProgressBar) findViewById(R.id.ek_articlelist_progressbar);
//		mProgressBar.setVisibility(View.VISIBLE);
		findViewById(R.id.imageButton_back).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
				
			}
		});
		mListview.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_FLING:
				case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
					// mBtnBack.setText("busy");
					isScrolling = true;
					break;
				case OnScrollListener.SCROLL_STATE_IDLE:
					// mBtnBack.setText("not busy");
					int first = view.getFirstVisiblePosition();
					int count = view.getChildCount();
					for (int i = 0; i < count; i++) {
						
						if (isAutoDownloadThumb && view.getAdapter().getItemViewType(first + i) != AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER) {
							getPhoto(first + i);
						}

					}
					isScrolling = false;
					break;
				}
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
//				if(isToLoad && totalItemCount - firstVisibleItem == visibleItemCount) {
////					Log.d(TAG, "totalItemCount:"+totalItemCount+";firstVisibleItem:"+firstVisibleItem+";visibleItemCount:"+visibleItemCount);
//					GetEkArticleList.GetHotEkArticleList(mSortId, mCurrentPos, ARTICLE_NUMBER, mHandler);
//					isToLoad = false;
//					enableFooter(true,false,false);
//				}
				if(view.getLastVisiblePosition()==view.getCount()-1){
					isScrolling = false;
				}
			}
		});
		mListview.setAdapter(mAdapter);
		setTitle(mSortTitle);
		enableFooter(true,false,false);
	}
	private boolean isToLoad;
	private boolean isScrolling;
	
	private class EKListAdapter extends SimpleAdapter {

		public EKListAdapter(Context context,
				List<? extends Map<String, ?>> data, int resource,
				String[] from, int[] to) {
			super(context, data, resource, from, to);
			// TODO Auto-generated constructor stub
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view = super.getView(position, convertView, parent);
			if(!isScrolling){
				getPhoto(position);
			}
			return view;
		}

		@Override
		public int getItemViewType(int position) {
			return position >= getCount() || position < 0 ? AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER
					: 0;
		}

	}
}
